﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.SessionState;
using System.Data;
using System.IO;
using Newtonsoft.Json;
using Framework.DataAccess;
using Framework.Common.JsonEntities;
using Framework.Common;
using Framework.Common.Common;
using Mode;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.POIFS;
using NPOI.Util;


namespace WebSite.WebServer
{
    /// <summary>
    /// DownloadExcel 的摘要说明
    /// </summary>
    public class DownloadExcel : IHttpHandler, IReadOnlySessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/x-excel";
            try
            {
                    //导出用户列表
                    string action = context.Request.Params["Action"];
                    if (context.Request.Params["Action"] == "UesrList")
                        UesrList();
                    else if (action == "ExportTopic")
                        ExportTopic();
                    else if (action == "ExportModel")
                        ExportModel();
                    else if (action == "ExportExamInfo")
                        ExportExamInfo();
                    else if (action == "ExportExamTable")
                        ExportExamTable();
                    else if (action == "AreRoleList")
                        AreRoleList();
            }
            catch (Exception err)
            {
                var message = err.Message;
                if (err.InnerException != null && err.InnerException.Message != null)
                    message += "<BR>" + err.InnerException.Message;
                context.Response.Write(message);
                context.Response.End();
            }

        }


        public void UesrList()
        {
            var context = System.Web.HttpContext.Current;

            loginInfo lu = chklogin();
            if (lu != null)
            {
                int areid = context.Request.Params["aid"].ToInt();
                int roleid = context.Request.Params["rid"].ToInt();
                int status = context.Request.Params["status"].ToInt();
                string name = context.Request.Params["userName"].ToString();
                    
                User u = new User();
                DataTable dt = u.MemberDownloadExecl(areid, roleid, status, name);


                ExportDataTableToExcel(dt, "用户", "用户列表");
            }
        }


        private void AreRoleList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
                return;


            role myRole = new role();
            int areid = context.Request.Params["aid"].ToInt();
            int status = context.Request.Params["status"].ToInt();
            string rolename = context.Request.Params["roleName"].ToString();

            DataTable dt = myRole.GetRoleExcel(areid, status, rolename);
            ExportDataTableToExcel(dt, "区域职务表", "区域职务列表");

        }

        //  导出题目
        private void ExportTopic()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
                return;

            context.Response.Clear();
            context.Response.ClearContent();
            context.Response.ClearHeaders();
            context.Response.Buffer = false;
            context.Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            context.Response.Expires = 0;
            context.Response.AddHeader("Pragma", "No-Cache");
            context.Response.AddHeader("Cache-Control", "Private");
            context.Response.CacheControl = "No-Cache";
            context.Response.ContentType = "application/ms-excel;charset=utf-8";
            context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("题目列表.xls"));

            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet one_sheet = generate_topic(1, workbook.CreateSheet("单选题"), workbook);
            HSSFSheet much_sheet = generate_topic(2, workbook.CreateSheet("多选题"), workbook);
            HSSFSheet judge_sheet = generate_topic(3, workbook.CreateSheet("判断题"), workbook);
            HSSFSheet fill_sheet = generate_topic(4, workbook.CreateSheet("填空题"), workbook);
            HSSFSheet query_sheet = generate_topic(5, workbook.CreateSheet("问答题"), workbook);
            HSSFSheet type_sheet = generate_type(workbook.CreateSheet("打字题"), workbook);


            workbook.Write(context.Response.OutputStream);

            one_sheet.Dispose();
            much_sheet.Dispose();
            judge_sheet.Dispose();
            fill_sheet.Dispose();
            query_sheet.Dispose();
            type_sheet.Dispose();

            workbook.Dispose();
        }

        private HSSFSheet generate_type(HSSFSheet sheet, HSSFWorkbook work)
        {
            int index = 1;
            List<TopicEx> list = Framework.DataAccess.ExportTopic.GetTopic(6);
            foreach (TopicEx item in list)
            {
                HSSFRow dataRow = sheet.CreateRow(index);

                // 添加题目ID
                HSSFCell cid = dataRow.CreateCell(0);
                cid.SetCellType(HSSFCellType.NUMERIC);
                cid.SetCellValue(item.id);
                cid.CellStyle.Alignment = CellHorizontalAlignment.CENTER_SELECTION;
                cid.CellStyle.VerticalAlignment = CellVerticalAlignment.CENTER;

                // 添加题目
                HSSFCell ctitle = dataRow.CreateCell(1);
                ctitle.SetCellType(HSSFCellType.STRING);
                ctitle.SetCellValue(item.title);

                // 添加题目状态
                HSSFCell stitle = dataRow.CreateCell(2);
                stitle.SetCellType(HSSFCellType.STRING);
                stitle.SetCellValue(item.status == 0 ? "启用" : "停用");

                index++;
            }

            return sheet;
        }

        private HSSFSheet generate_topic(int stype, HSSFSheet sheet, HSSFWorkbook work)
        {
            int index = 1;

            HSSFCellStyle asw_style = work.CreateCellStyle();
            asw_style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.WHITE.index;
            asw_style.FillPattern = CellFillPattern.ALT_BARS;
            asw_style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.GREEN.index;

            List<TopicEx> list = Framework.DataAccess.ExportTopic.GetTopic(stype);
            foreach (TopicEx item in list)
            {
                List<Answer> al = item.Answer;
                HSSFRow dataRow = sheet.CreateRow(index);

                // 添加题目ID
                HSSFCell cid = dataRow.CreateCell(0);
                cid.SetCellType(HSSFCellType.NUMERIC);
                cid.SetCellValue(item.id);
                cid.CellStyle.Alignment = CellHorizontalAlignment.CENTER_SELECTION;
                cid.CellStyle.VerticalAlignment = CellVerticalAlignment.CENTER;

                // 添加题目
                HSSFCell ctitle = dataRow.CreateCell(1);
                sheet.AddMergedRegion(new NPOI.HSSF.Util.Region(index, 1, index, al.Count));
                ctitle.SetCellType(HSSFCellType.STRING);
                ctitle.SetCellValue(item.title);
                ctitle.CellStyle.Alignment = CellHorizontalAlignment.LEFT;
                ctitle.CellStyle.VerticalAlignment = CellVerticalAlignment.CENTER;

                // 添加题目状态
                HSSFCell stitle = dataRow.CreateCell(al.Count + 1);
                stitle.SetCellType(HSSFCellType.STRING);
                stitle.SetCellValue(item.status == 0 ? "启用" : "停用");


                index++;

                HSSFRow answerRow = sheet.CreateRow(index);
                for (int acol = 0; acol < al.Count; acol++)
                {
                    HSSFCell asw = answerRow.CreateCell(acol + 1);
                    asw.SetCellType(HSSFCellType.STRING);
                    asw.SetCellValue(al[acol].title);

                    if (al[acol].right)
                        asw.CellStyle = asw_style;
                }


                // 合并ID
                sheet.AddMergedRegion(new NPOI.HSSF.Util.Region(index - 1, 0, index, 0));
                // 合并状态 
                sheet.AddMergedRegion(new NPOI.HSSF.Util.Region(index - 1, al.Count + 1, index, al.Count + 1));

                index++;
            }

            return sheet;
        }

        private void ExportModel()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
                return;

            int areid = context.Request.Params["aid"].ToInt();
            int? roleid = context.Request.Params["rid"].ToInt();

            int typeID = context.Request.Params["type"].ToInt();
            DateTime? beginDate = context.Request.Params["beginDate"].ToDateNull();
            DateTime? endDate = context.Request.Params["endDate"].ToDateNull();
            string title = context.Request.Params["title"].ToStr();
            int status = context.Request.Params["status"].ToInt();

            //如果不是超级管理员，则将区域ID设置成登录的区域ID
            if (loginUser.A_LEVEL != 0 || loginUser.R_POWER != 1)
                areid = loginUser.A_ID;

            ModeAdpater ma = new ModeAdpater();
            PageList<object> List = ma.GetExcel(status, typeID, areid, (roleid == -1 ? null : roleid), beginDate, endDate, title);
            List.Data.Columns.Add("stat", typeof(string));
            List.Data.Columns.Add("tp", typeof(string));

            foreach (DataRow row in List.Data.Rows)
            {
                int type = row["type"].ToInt();
                row["tp"] = type == 0 ? "随机模型" : "手工模型";

                type = row["status"].ToInt();
                row["stat"] = type == 0 ? "启用" : "停用";
            }

            List.Data.Columns["name"].ColumnName = "模型名称";
            List.Data.Columns["tp"].ColumnName = "模型类型";
            List.Data.Columns["date"].ColumnName = "创建日期";
            List.Data.Columns["exam"].ColumnName = "创建考场次数";
            List.Data.Columns["stat"].ColumnName = "模型状态";
            List.Data.Columns["model_score"].ColumnName = "模型总分";

            List.Data.Columns.Remove("status");
            List.Data.Columns.Remove("has_QA");
            List.Data.Columns.Remove("rolename");
            List.Data.Columns.Remove("arename");
            List.Data.Columns.Remove("type");

            ExportDataTableToExcel(List.Data, "模型列表", "模型列表");
        }

        //
        private void ExportExamInfo()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();

            if (lu != null)
            {
                int examid = context.Request.Params["examid"].ToInt(0);
                ExportExam ee = new ExportExam( examid );
                DataSet ds = ee.ExportExamDataSet();

                
                ExportDataTableToExcel(ds, "考场信息");
            }
        }



        private void ExportExamTable()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();

            if (lu != null)
            {

                examinationDA myExam = new examinationDA();

                int areID = context.Request.Params["areID"].ToInt();
                int modelID = context.Request.Params["modelID"].ToInt();
                string name = context.Request.Params["name"].ToStr();
                int status = context.Request.Params["status"].ToInt();
                DateTime? beginDate = context.Request.Params["beginDate"].ToDateNull();
                DateTime? endDate = context.Request.Params["endDate"].ToDateNull();

                ExportExam ee = new ExportExam();
                DataTable dt = ee.ExportExamListGetExamList(areID, modelID, status, name, beginDate, endDate);


                ExportDataTableToExcel(dt, "考场列表", "考场列表");
            }

        }


        //private void ExportTopic()
        //{
        //    loginInfo lu = chklogin();
        //    if (lu == null)
        //        return;
        //    var context = System.Web.HttpContext.Current;

        //    Topic topic = new Topic();

        //    int? typeID = context.Request.Params["typeID"].ToIntNull();
        //    int? roleID = context.Request.Params["roleID"].ToIntNull();
        //    DateTime? beginDate = context.Request.Params["beginDate"].ToDateNull();
        //    DateTime? endDate = context.Request.Params["endDate"].ToDateNull();
        //    string title = context.Request.Params["title"];
        //    int? status = context.Request.Params["status"].ToInt(-1);

        //    PageView pageInfo = new PageView();
        //    pageInfo.PageIndex = context.Request.Params["page"].ToInt(1);
        //    //pageInfo.PageSize = context.Request.Params["pagesize"].ToInt(20);
        //    pageInfo.PageSize = int.MaxValue;
        //    pageInfo.SortName = context.Request.Params["sortname"].ToStr();
        //    pageInfo.SortOrder = context.Request.Params["sortorder"].ToStr();
        //    pageInfo.SearchParams = context.Request.Params;

        //    PageList<object> List = topic.GetTopicList(pageInfo, (typeID <= 0 ? null : typeID), roleID, beginDate, endDate, title, status <= 0 ? null : status);
        //    List.Data.Columns.Add("题型", typeof(string));
        //    List.Data.Columns["T_TITLE"].ColumnName = "题目名称";
        //    List.Data.Columns["T_DATE"].ColumnName = "创建日期";
        //    List.Data.Columns["R_NAME"].ColumnName = "职务";
        //    foreach (DataRow dr in List.Data.Rows)
        //    {
        //        int type = Convert.ToInt32(dr["T_TYPE"]);
        //        if (type == 1)
        //            dr["题型"] = "单选题";
        //        else if (type == 2)
        //            dr["题型"] = "多选题";
        //        else if (type == 3)
        //            dr["题型"] = "判断题";
        //        else if (type == 4)
        //            dr["题型"] = "填空题";
        //        else if (type == 5)
        //            dr["题型"] = "问答题";
        //        else if (type == 2)
        //            dr["题型"] = "打字题";
        //    }
        //    List.Data.Columns.Remove("T_TYPE");
        //    List.Data.Columns.Remove("rows");
        //    List.Data.Columns.Remove("T_ID");
        //    List.Data.Columns.Remove("R_ID");
        //    List.Data.Columns.Remove("T_STATUS");
        //    List.Data.Columns.Remove("R_POWER");
        //    List.Data.Columns.Remove("R_REMARK");
        //    List.Data.Columns.Remove("R_DATE");
        //    ExportDataTableToExcel(List.Data, "题库", "题库");
        //}

        public void ExportDataTableToExcel(DataTable sourceTable, string sheetName, string fileName)
        {
            var context = System.Web.HttpContext.Current;
            context.Response.Clear();
            context.Response.ClearContent();
            context.Response.ClearHeaders();
            context.Response.Buffer = false;
            context.Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            context.Response.Expires = 0;
            context.Response.AddHeader("Pragma", "No-Cache");
            context.Response.AddHeader("Cache-Control", "Private");
            context.Response.CacheControl = "No-Cache";
            context.Response.ContentType = "application/ms-excel;charset=utf-8";
            context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName + ".xls"));
            /*
           context.Response.ContentType = "application/x-excel";
           fileName = HttpUtility.UrlEncode(fileName + ".xls");
           context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
             */

            HSSFWorkbook workbook = new HSSFWorkbook();
            MemoryStream ms = new MemoryStream();
            HSSFSheet sheet = workbook.CreateSheet(sheetName);
            HSSFRow headerRow = sheet.CreateRow(0);
            // handling header.       
            foreach (DataColumn column in sourceTable.Columns)
                headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
            // handling value.       
            int rowIndex = 1;

            foreach (DataRow row in sourceTable.Rows)
            {
                HSSFRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in sourceTable.Columns)
                {
                    dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                }
                rowIndex++;
            }
            workbook.Write(context.Response.OutputStream);

            sheet = null;
            headerRow = null;
            workbook = null;

        }



        public void ExportDataTableToExcel(DataSet sourceData,  string fileName)
        {
            var context = System.Web.HttpContext.Current;
            context.Response.Clear();
            context.Response.ClearContent();
            context.Response.ClearHeaders();
            context.Response.Buffer = false;
            context.Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            context.Response.Expires = 0;
            context.Response.AddHeader("Pragma", "No-Cache");
            context.Response.AddHeader("Cache-Control", "Private");
            context.Response.CacheControl = "No-Cache";
            context.Response.ContentType = "application/ms-excel;charset=utf-8";
            context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName + ".xls"));

            HSSFWorkbook workbook = new HSSFWorkbook();
            //MemoryStream ms = new MemoryStream();
            foreach (DataTable dt in sourceData.Tables)
            {
                HSSFSheet sheet = workbook.CreateSheet(dt.TableName);
                HSSFRow headerRow = sheet.CreateRow(0);

                // handling header.       
                foreach (DataColumn column in dt.Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);

                for (int index = 0; index < dt.Rows.Count; index++)
                {
                    DataRow row = dt.Rows[index];
                    HSSFRow dataRow = sheet.CreateRow(index+1);

                    foreach (DataColumn column in dt.Columns)
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                }
            }

            workbook.Write(context.Response.OutputStream);

            workbook = null;
        }



        loginInfo chklogin()
        {
            try
            {
                return SessionShard.loginUser;
            }
            catch
            {

                return null;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
